package com.example.demo.until;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static String md5(String input) {
        try {
            // 创建一个MessageDigest实例，指定MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 对输入的字符串进行摘要计算
            byte[] digest = md.digest(input.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }

    public static String md5(String input, String salt) {
        try {
            // 创建一个MessageDigest实例，指定MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将盐值添加到输入字符串中
            input += salt;
            // 对添加盐值后的字符串进行摘要计算
            byte[] digest = md.digest(input.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }

    public static void main(String[] args) {
        String input = "Hello, World!";
        String encrypted = md5(input);
        System.out.println("原始字符串： " + input);
        System.out.println("MD5加密后： " + encrypted);
//afe77db521c64f8f84bab3c5dcf0a15e

        input = "afe77db521c64f8f84bab3c5dcf0a15e";
        System.out.println("带盐加密： " );
        String salt = "yuandianServer";
         encrypted = md5(input, salt);
        System.out.println("原始字符串： " + input);
        System.out.println("带盐的MD5加密后： " + encrypted);
    }
}
